import React, { useState, useEffect } from 'react';
import { Card, Avatar, Button, List, Typography, Tag, Empty, message } from 'antd';
import { UserOutlined, ShoppingOutlined, HeartOutlined, SettingOutlined, LogoutOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { User, Order } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text } = Typography;

const Profile: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    const userData = Storage.get<User>(STORAGE_KEYS.USER);
    const orderData = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
    
    if (!userData) {
      navigate('/login');
      return;
    }
    
    setUser(userData);
    setOrders(orderData.filter(order => order.userId === userData.id));
  }, [navigate]);

  const handleLogout = () => {
    Storage.remove(STORAGE_KEYS.USER);
    message.success('已退出登录');
    navigate('/');
  };

  const getStatusInfo = (status: Order['status']) => {
    const statusMap = {
      pending: { text: '待付款', color: 'orange' },
      paid: { text: '已付款', color: 'blue' },
      shipped: { text: '已发货', color: 'cyan' },
      delivered: { text: '已送达', color: 'green' },
      cancelled: { text: '已取消', color: 'red' }
    };
    return statusMap[status];
  };

  const menuItems = [
    {
      title: '我的订单',
      icon: <ShoppingOutlined />,
      description: '查看全部订单',
      onClick: () => navigate('/orders')
    },
    {
      title: '我的收藏',
      icon: <HeartOutlined />,
      description: '收藏的商品',
      onClick: () => message.info('功能开发中')
    },
    {
      title: '账户设置',
      icon: <SettingOutlined />,
      description: '个人信息设置',
      onClick: () => message.info('功能开发中')
    },
    {
      title: '退出登录',
      icon: <LogoutOutlined />,
      description: '安全退出',
      onClick: handleLogout
    }
  ];

  if (!user) {
    return null;
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      {/* 用户信息 */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
          <Avatar 
            size={80} 
            src={user.avatar} 
            icon={<UserOutlined />}
            style={{ marginRight: 16 }}
          />
          <div>
            <Title level={3} style={{ margin: 0 }}>
              {user.username}
            </Title>
            <Text type="secondary">手机号：{user.phone}</Text>
            <br />
            <Text type="secondary">邮箱：{user.email}</Text>
          </div>
        </div>
      </Card>

      {/* 功能菜单 */}
      <Card title="我的服务" style={{ marginBottom: 16 }}>
        <List
          dataSource={menuItems}
          renderItem={(item) => (
            <List.Item 
              onClick={item.onClick}
              style={{ cursor: 'pointer', padding: '16px' }}
              className="profile-menu-item"
            >
              <List.Item.Meta
                avatar={item.icon}
                title={item.title}
                description={item.description}
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 最近订单 */}
      <Card title="最近订单">
        {orders.length > 0 ? (
          <List
            dataSource={orders.slice(0, 3)}
            renderItem={(order) => {
              const statusInfo = getStatusInfo(order.status);
              return (
                <List.Item 
                  onClick={() => navigate(`/order/${order.id}`)}
                  style={{ cursor: 'pointer' }}
                >
                  <List.Item.Meta
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Text>订单号：{order.id}</Text>
                        <Tag color={statusInfo.color}>{statusInfo.text}</Tag>
                      </div>
                    }
                    description={
                      <div>
                        <Text>共 {order.items.length} 件商品</Text>
                        <Text style={{ float: 'right' }} className="price-current">
                          ¥{order.totalAmount.toFixed(2)}
                        </Text>
                      </div>
                    }
                  />
                </List.Item>
              );
            }}
          />
        ) : (
          <Empty description="暂无订单" />
        )}
        
        {orders.length > 3 && (
          <div style={{ textAlign: 'center', marginTop: 16 }}>
            <Button type="link" onClick={() => navigate('/orders')}>
              查看全部订单
            </Button>
          </div>
        )}
      </Card>
    </div>
  );
};

export default Profile;
